/**
 * 
 */
package pl.net.beercrm.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.net.beercrm.dao.GenericDao;
import pl.net.beercrm.model.Ingredient;

/**
 * @author Rafi
 * 
 */
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class IngredientService implements GenericService<Ingredient, Long> {

	@Autowired
	private GenericDao<Ingredient, Long> ingredientDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#upsert(java.lang.Object)
	 */
	@Override
	public void upsert(Ingredient object) {
		List<Ingredient> persistedObjects = findByGuid(object.getIngredientId());
		if (persistedObjects.size() > 0) {
			boolean addAmount = true;
			for (Ingredient ingredient : persistedObjects) {
				if (ingredient.getAmount() == object.getAmount()) {
					addAmount = false;
				}
			}
			if (addAmount) {
				ingredientDao.create(object);
			}
		} else {
			ingredientDao.create(object);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#delete(java.lang.Object)
	 */
	@Override
	public void delete(Ingredient object) {
		List<Ingredient> persistedObjects = findByGuid(object.getIngredientId());
		for (Ingredient ingredient : persistedObjects) {
			ingredientDao.delete(ingredient);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#find(java.io.Serializable)
	 */
	@Override
	public Ingredient find(Long id) {
		return ingredientDao.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#findByGuid(java.lang.String)
	 */
	@Override
	public List<Ingredient> findByGuid(String guid) {
		return ingredientDao.findAllByProperty("ingredientId", guid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#list()
	 */
	@Override
	public List<Ingredient> list() {
		return ingredientDao.findAll();
	}

	/* (non-Javadoc)
	 * @see pl.net.beercrm.service.GenericService#findByProperty(java.lang.String, java.lang.Object)
	 */
	@Override
	public List<Ingredient> findByProperty(String property, Object value) {
		return ingredientDao.findAllByProperty(property, value);
	}

}
